<template>
  <div id="sysUser">
    <el-form
      :inline="true"
      :model="sysUserQueryRequest"
      class="demo-form-inline"
    >
      <el-form-item label="用户名">
        <el-input
          v-model="sysUserQueryRequest.username"
          placeholder="用户名"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="sysUserQueryRequest.createTimeBegin"
          type="date"
          placeholder="Pick a date"
          clearable
        />
        -
        <el-date-picker
          v-model="sysUserQueryRequest.createTimeEnd"
          type="date"
          placeholder="Pick a date"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPage">查找</el-button>
      </el-form-item>
    </el-form>
    <div class="addUserButton" style="margin: 5px; padding: 5px;">
      <el-button type="success" round @click="addShow">+ 添加</el-button>
      <el-button type="primary" round @click="reset">重置</el-button>
      <el-button type="danger" round @click="batchDelete">批量删除</el-button>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="changeSelections"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="id" label="id" width="120" />
        <el-table-column property="username" label="用户名" />
        <el-table-column property="phone" label="手机号" />
        <el-table-column property="avatar" label="头像">
          <template #default="scope">
            <el-image :src="scope.row.avatar" style="width: 80px" />
          </template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间" />
        <el-table-column property="status" label="状态">
          <template #default="scope">
            <div v-if="scope.row.status === 1">
              <el-button type="success" disabled>正常</el-button>
            </div>
            <div v-else>
              <el-button type="info" disabled>失效</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="warning" @click="findUser(scope.row)">
              修改
            </el-button>
            <el-button type="primary" @click="showUserRoles(scope.row.id)">
              分配角色
            </el-button>
            <el-button type="danger" @click="deleteUser(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        class=" pagination-container
            "
      >
        <el-pagination
          v-model:current-page="page.pageNum"
          v-model:page-size="page.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="fetchPage"
          @current-change="fetchPage"
        />
      </div>
    </div>
    <!-- 添加\修改用户表单对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
      <el-form label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="sysUser.username" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="sysUser.phone" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/admin/system/avatarUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="header"
          >
            <el-image
              v-if="sysUser.avatar"
              :src="sysUser.avatar"
              style="width: 80px"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <div v-if="sysUser.id">
            <el-button type="primary" @click="changeUser">
              提交
            </el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="addUser">提交</el-button>
          </div>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--分配角色-->
    <el-dialog v-model="dialogVisibleRole" title="分配角色" width="30%">
      <el-form label-width="120px">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group
          v-model="checkedRoles"
          @change="handleCheckedRolesChange"
        >
          <el-checkbox
            v-for="role in roles"
            :key="role.id"
            :label="role.id"
            :value="role.id"
          >
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
        <el-form-item>
          <el-button type="primary" @click="assignRoles">
            提交
          </el-button>
          <el-button @click="dialogVisibleRole = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox, ElTable, UploadProps } from 'element-plus'
import {
  getUserList,
  doAddUser,
  updateUser,
  deleteUserById,
  doBatchDelete,
  findRoles,
  findRolesByUserId,
  assignUserRole,
} from '@/api/sysUser.js'
import { useApp } from '@/pinia/modules/app'

onMounted(async () => {
  await fetchPage()
  await showRoles()
})
const dialogVisibleRole = ref(false)
let selections = []
const dialogVisible = ref(false)
const sysUserQueryRequest = reactive({
  username: '',
  createTimeBegin: '',
  createTimeEnd: '',
})
const sysUser = reactive({
  id: '',
  username: '',
  phone: '',
  avatar: '',
})
const page = reactive({
  pageSize: 4,
  pageNum: 1,
  total: '',
})
const tableData = ref([])
const fetchPage = async () => {
  const ref = await getUserList(
    page.pageNum,
    page.pageSize,
    sysUserQueryRequest
  )
  if (ref.code === 200) {
    tableData.value = ref.data.records
    page.total = ref.data.total
  }
}
// 重置
const reset = () => {
  page.pageNum = 1
  page.pageSize = 4
  sysUserQueryRequest.createTimeBegin = ''
  sysUserQueryRequest.createTimeEnd = ''
  sysUserQueryRequest.username = ''
  sysUser.id = ''
  sysUser.username = ''
  sysUser.phone = ''
  sysUser.avatar = ''
  fetchPage()
}
// 添加用户 1、展示用户信息
const addShow = () => {
  sysUser.avatar = ''
  sysUser.id = ''
  sysUser.phone = ''
  sysUser.username = ''
  dialogVisible.value = true
}
// 添加用户 2、添加用户
const addUser = async () => {
  dialogVisible.value = false
  const ref = await doAddUser(sysUser)
  if (ref.code === 200) {
    ElMessage.success('添加成功')
  } else {
    ElMessage.error(ref.message)
  }
  fetchPage()
}

// 修改用户 1、查询当前用户信息
const findUser = async row => {
  sysUser.id = row.id
  // const { data } = await findUserById(id);
  sysUser.username = row.username
  sysUser.phone = row.phone
  sysUser.avatar = row.avatar
  dialogVisible.value = true
}
// 修改用户 2、修改用户信息
const changeUser = async () => {
  dialogVisible.value = false
  const ref = await updateUser(sysUser)
  if (ref.code === 200) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(ref.message)
  }
  fetchPage()
}
// 删除用户
const deleteUser = async id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ref = await deleteUserById(id)
      if (ref.code === 200) {
        ElMessage.success('删除成功')
        fetchPage()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

// 批量删除
const changeSelections = selection => {
  selections = selection
}

const batchDelete = async () => {
  if (selections.length === 0) {
    ElMessage.warning('请选择删除对象')
    return
  }
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      var ids = []
      selections.forEach(element => {
        ids.push(element.id)
      })
      const { code, message } = await doBatchDelete(ids)
      if (code === 200) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
  fetchPage()
}
// 头像
const header = {
  token: useApp().authorization.token,
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  sysUser.avatar = response.data
}
// 分配角色 1、展示角色列表 已经对所属角色进行勾选
const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedRoles = ref([])
const roles = ref([])

// 查询所有角色
const showRoles = async () => {
  const ref = await findRoles()
  roles.value = ref.data
}

const assignUserId = ref('')
// 查询当前用户的角色 并展示分配界面
const showUserRoles = async id => {
  checkedRoles.value = []
  assignUserId.value = id
  //用户角色查询
  const { code, data, message } = await findRolesByUserId(id)
  if (code === 200) {
    data.forEach(element => {
      checkedRoles.value.push(element.id)
    })
    handleCheckedRolesChange(checkedRoles.value)
  } else {
    ElMessage.error('查询失败')
  }
  dialogVisibleRole.value = true
}
// 分配角色
const assignRoles = async () => {
  const ref = await assignUserRole(assignUserId.value, checkedRoles.value)
  if (ref.code === 200) {
    ElMessage.success('分配成功')
  } else {
    ElMessage.error('分配失败')
  }
  dialogVisibleRole.value = false
}
// 修改全选状态
const handleCheckAllChange = (val: boolean) => {
  if (val) {
    roles.value.forEach(element => {
      checkedRoles.value.push(element.id)
    })
  } else {
    checkedRoles.value = []
  }
  isIndeterminate.value = false
}
// 检查是否全选  选择角色发生变化
const handleCheckedRolesChange = (value: []) => {
  checkedRoles.value = value
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}
</script>

<style scoped>
#sysUser .pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin: 20px 0; /* 可选：添加上下间距 */
}

.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin: 20px 0; /* 可选：添加上下间距 */
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);

  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
